package com.dong.servlet.Provider;

import com.alibaba.fastjson.JSONArray;
import com.dong.pojo.Provider;
import com.dong.pojo.User;
import com.dong.service.Provider.ProviderService;
import com.dong.service.Provider.ProviderServiceImpl;
import com.dong.util.Constants;
import com.dong.util.PageSupport;
import com.dong.util.pagesize;
import com.microsoft.sqlserver.jdbc.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

public class ProviderServlet extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method.equals("add") && method != null){
            this.add(req,resp);
        }else if(method.equals("query") && method != null){
            this.query(req,resp);
        }else if(method.equals("view")&& method != null){
            this.getProviderById(req,resp,"providerview.jsp");
        }else if(method.equals("modify") && method != null){
            this.getProviderById(req,resp,"providermodify.jsp");
        }else if(method.equals("modifysave") && method != null){
            this.modifyProvider(req,resp);
        }
    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
    //增加供应商
    private void add(HttpServletRequest req,HttpServletResponse resp) throws IOException, ServletException {
        System.out.println("add()================");
        String proCode = req.getParameter("proCode");
        String proName = req.getParameter("proName");
        String proContact = req.getParameter("proContact");
        String proPhone = req.getParameter("proPhone");
        String proAddress = req.getParameter("proAddress");
        String proFax = req.getParameter("proFax");
        String proDesc = req.getParameter("proDesc");

        Provider provider = new Provider();
        provider.setProCode(proCode);
        provider.setProName(proName);
        provider.setProContact(proContact);
        provider.setProPhone(proPhone);
        provider.setProAddress(proAddress);
        provider.setProFax(proFax);
        provider.setProDesc(proDesc);
        provider.setCreationDate(new Date());
        provider.setCreatedBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId());

        ProviderService providerService = new ProviderServiceImpl();
        if(providerService.add(provider)){
            resp.sendRedirect(req.getContextPath() + "/jsp/provider.do?method=query");
        }else{
            req.getRequestDispatcher("provideradd.jsp").forward(req,resp);
        }
    }
    //通过供应商名称、编码获取供应商列表
    private void query(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
        String pageIndex = req.getParameter("pageIndex");
        String queryProName = req.getParameter("queryProName");
        String queryProCode = req.getParameter("queryProCode");
        ProviderService providerService = new ProviderServiceImpl();
        if(StringUtils.isEmpty(queryProName)){
            queryProName = "";
        }
        if(StringUtils.isEmpty(queryProCode)){
            queryProCode = "";
        }

        //第一次走这个请求，一定是第一页，页面大小固定
        int pageSize = pagesize.pageSize;
        int currentPageNo = 1;

        if(pageIndex != null){
            //可以加try/catch
            currentPageNo = Integer.parseInt(pageIndex);
        }
        //获取用户总数(分页上一页和下一页的情况)
        int totalCount = providerService.getUserCount(queryProName,queryProCode);
        //总页数支持
        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(totalCount);

        int totalPageCount = ((int)(totalCount/pageSize))+1;//总共有几页
        //控制首页和尾页
        //若果页面小于1，就显示第一页的东西
        if(currentPageNo < 1){
            currentPageNo = 1;
        }else if(currentPageNo > totalPageCount){//当前页面大于总页数时返回最后一页
            currentPageNo = totalPageCount;
        }

        List<Provider> ProviderList = new ArrayList<Provider>();
        ProviderList = providerService.getProviderList(queryProName, queryProCode,currentPageNo, pageSize);
        req.setAttribute("providerList",ProviderList);
        req.setAttribute("queryProName",queryProName);
        req.setAttribute("queryProCode",queryProCode);
        req.setAttribute("totalCount",totalCount);
        req.setAttribute("currentPageNo",currentPageNo);
        req.setAttribute("totalPageCount",totalPageCount);
        try {
            req.getRequestDispatcher("providerlist.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    //通过供应商id查找供应商
    private void getProviderById(HttpServletRequest req,HttpServletResponse resp,String url) throws ServletException, IOException {
        String id = req.getParameter("proid");
        if(!StringUtils.isEmpty(id)){
            ProviderService providerService = new ProviderServiceImpl();
            Provider provider = null;
            provider = providerService.getProviderById(id);
            req.setAttribute("provider",provider);
            req.getRequestDispatcher(url).forward(req,resp);
        }
    }
    //修改供应商信息
    private void modifyProvider(HttpServletRequest req,HttpServletResponse resp) throws IOException, ServletException {
        System.out.println("modify()================");
        String providerid = req.getParameter("id");
        String proCode = req.getParameter("proCode");
        String proName = req.getParameter("proName");
        String proContact = req.getParameter("proContact");
        String proPhone = req.getParameter("proPhone");
        String proAddress = req.getParameter("proAddress");
        String proFax = req.getParameter("proFax");
        String proDesc = req.getParameter("proDesc");

        Provider provider = new Provider();
        provider.setId(Integer.valueOf(providerid));
        provider.setProCode(proCode);
        provider.setProName(proName);
        provider.setProContact(proContact);
        provider.setProPhone(proPhone);
        provider.setProAddress(proAddress);
        provider.setProFax(proFax);
        provider.setProDesc(proDesc);
        provider.setModifyDate(new Date());
        provider.setModifyBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId());
        ProviderService providerService = new ProviderServiceImpl();

        if(providerService.modifyProvider(provider)){
            resp.sendRedirect(req.getContextPath()+"/jsp/provider.do?method=query");
        }else {
            req.getRequestDispatcher("providermodify.jsp").forward(req,resp);
        }
    }
    //通过id删除供应商
    private void delProvider(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        String id = req.getParameter("proid");
        HashMap<String, String> resultMap = new HashMap<String, String>();
        if(StringUtils.isEmpty(id)){
            ProviderService providerService = new ProviderServiceImpl();
            int flag = providerService.deleteProviderById(id);
            if(flag == 0){//删除成功
                resultMap.put("delResult", "true");
            }else if(flag == -1){//删除失败
                resultMap.put("delResult", "false");
            }else if(flag > 0){//该供应商下有订单，不能删除，返回订单数
                resultMap.put("delResult", String.valueOf(flag));
            }
        }else{
            resultMap.put("delResult", "notexit");
        }
        //把resultMap转换成json对象输出
        resp.setContentType("application/json");
        PrintWriter outPrintWriter = resp.getWriter();
        outPrintWriter.write(JSONArray.toJSONString(resultMap));
        outPrintWriter.flush();
        outPrintWriter.close();
    }
}
